package com.cp.rabbitmq.workqueue;

import com.cp.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Coder编程
 * @version V1.0
 * @Title: ConsumerTwo
 * @Package: com.cp.rabbitmq.workqueue
 * @Description: 接受消息
 * @date 2019/7/9  22:24
 **/

public class ConsumerTwo {

    private static final String  QUEUE_NAME="TEST_WORK_QUEUE";

    public static void main(String[] args) throws IOException, TimeoutException {

        //获取连接
        Connection connection = ConnectionUtils.getConnection();
        //获取channel
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //定义一个消费者
        Consumer consumer=new DefaultConsumer(channel){
            //消息到达 触发这个方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {

                String msg=new String(body,"utf-8");
                System.out.println("[ConsumerTwo] Received msg:"+msg);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    System.out.println("[ConsumerTwo] done ");
                }
            }
        };

        boolean autoAck=true;
        channel.basicConsume(QUEUE_NAME,autoAck , consumer);
    }
}
